import React, { useEffect, useState } from 'react';
import Taro from '@tarojs/taro';
import utils from '@/utils/index';
import { Button, Textarea, View } from '@tarojs/components';
import CommentImagePicker from '@/components/Comment/ImagePicker';
import CommentRate from '@/components/Comment/Rate';

import {
  commentUploadImgServer,
  confirmLocalCommentServer,
  getCommentScoreTypeServer,
} from '@/services/comment';

const toast = (title, callback) => {
  callback = callback || (() => {});
  Taro.showToast({ title, icon: 'none', duration: 1000 });
  setTimeout(() => {
    callback();
  }, 1000);
};

const Location = ({ order = {} }) => {
  //提交评价的数据
  const [state, updateState] = useState({
    topicId: 0,
    content: '',
    scoreTypeId: 0,
    imgUrls: '',
    score: 0,
  });

  const [uploadMap, setUploadMap] = useState({});

  const [locationScoreType, setLocationScoreType] = useState(null);

  const setState = (val) => {
    const res = { ...state, ...val };
    updateState(res);
  };

  //初始化
  const init = async () => {
    state.topicId = order.storeId;
    if (order.type != 0) {
      state.orderId = order.id;
    }
    //本地生活评分类型
    const locationScoreTypeRes = await getCommentScoreTypeServer({ appId: 'thjs_locallife_org' });
    if (locationScoreTypeRes.code === '1' && locationScoreTypeRes.content.length) {
      setLocationScoreType(locationScoreTypeRes.content[0]);
      state.scoreTypeId = locationScoreTypeRes.content[0].scoreTypeId;
    }
    setState(state);
  };

  useEffect(() => {
    order.storeId && init();
  }, [order]);

  //选择图片
  const handleImagePicker = (files) => {
    state.imgUrls = files.join(',');
    setState(state);
  };

  //评分
  const handleRate = (val) => {
    state.score = val;
    setState(state);
  };

  //评价内容
  const handleInput = (val) => {
    state.content = val.detail.value;
    setState(state);
  };

  //提交评价
  const confirm = async () => {
    let params = JSON.parse(JSON.stringify(state));
    if (params.score == 0) {
      toast('您还没有为星级打分');
      return;
    }
    Taro.showLoading({ title: '提交中~', mask: true });
    let files = {};
    const imgUrls = params.imgUrls ? params.imgUrls.split(',') : [];
    for (let file of imgUrls) {
      console.log('file:', file);
      if (!!uploadMap[file]) {
        //避免重复上传
        files[file] = uploadMap[file];
        continue;
      }
      const fileRes = await commentUploadImgServer(file);
      console.log('fileRes:', fileRes);
      if (fileRes.code == 1 && fileRes.content) {
        files[file] = fileRes.content;
      }
    }
    setUploadMap({
      ...uploadMap,
      ...files,
    });
    params.imgUrls = Object.values(files).join(',');
    confirmLocalCommentServer(params).then((res) => {
      Taro.hideLoading();
      if (res.code == 1) {
        toast('提交成功', () => {
          utils.backWithRefreash();
        });
      } else {
        toast(res.message);
      }
    });
  };

  return (
    <View className="submitCommentPage">
      <View className="submitCommentContent">
        <View className="part2">
          <View className="partContent">
            <View className="shopTitle">{order.storeName}</View>
            {/*评价打分*/}
            {!!locationScoreType && (
              <View className="shopRate">
                <CommentRate showText value={state.score} onChange={handleRate}>
                  {locationScoreType.name}
                </CommentRate>
              </View>
            )}
            {/*评价内容*/}
            <Textarea
              className="textarea"
              onInput={handleInput}
              placeholder="从多个角度评价宝贝，可以帮助更多想买的人"
              maxlength={120}
            />
            {/*买家图片*/}
            <CommentImagePicker onChange={handleImagePicker} />
          </View>
        </View>
        <View className="part3 flexMiddle">
          <Button className="btn customePageBackgroundStyle flexMiddle" onClick={confirm}>
            提交评价
          </Button>
        </View>
      </View>
    </View>
  );
};

export default Location;
